package org.deri.socializer.com.xmpp;

import java.util.HashMap;
import java.util.Iterator;

import org.deri.socializer.activities.chat.Participant;
import org.deri.socializer.activities.chat.ParticipantChat;
import org.deri.socializer.util.XMPPUtilities;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

public class XmppPrivateChat extends XmppChat {

	private XmppClient xmppClient;
	private Chat chat;
	private ParticipantChat self;
	
	
	
	public XmppPrivateChat(XmppClient xmppClient, ParticipantChat participant) {
		this.jid = participant.getJid();
		this.xmppClient = xmppClient;
		this.participants = new HashMap<String, Participant>();
		this.participants.put(participant.getUser(), participant);
		this.conversationHistory = new XmppConversationHistory(this);
		this.self = new ParticipantChat(XMPPUtilities.getSenderAddress(this.xmppClient.getXMPPUser().getJID()));
		this.chat = this.xmppClient.getXMPPConnection().getChatManager().createChat(participant.getJid(), null);
	}
	
	
	public void handleMessage(Message message) {
		this.conversationHistory.addMessage(message);
		//this.xmppClient.handleChatMessage(message);
	}

	
	public void sendMessage(String subject, String message) throws XMPPException {
		Iterator<String> participantsIter = this.participants.keySet().iterator();
		String userJid = "";
		while (participantsIter.hasNext()) 
			userJid = participantsIter.next();

		Message msg = new Message(userJid, Message.Type.chat);
		msg.setFrom(this.self.getJid());
		if (message != null) msg.setBody(message);
		if (subject != null) msg.setSubject(subject);
		try {
			this.chat.sendMessage(message);
			this.xmppClient.getChatActivity().displayChatMessage(this.self, message);
			this.conversationHistory.addMessage(msg);
		} catch (XMPPException e) {
			e.printStackTrace();
		}
	}
}
